package demo;

import Annotation.Component;
import Annotation.Scope;
import demo.Definition;
import demo.Scan;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ContainerFactory {
    //单例的容器
    private static Map<String,Object> singleton=new HashMap<String,Object>();

    //原型的容器
    private static Map<String, Definition> prototype=new HashMap<String,Definition>();

    public ContainerFactory(String path) throws InstantiationException, IllegalAccessException {
        //先初始化原型容器
        initPrototype(path);
        //初始化单例容器
        initSingleton();
    }

    //原型的容器
    private void initPrototype(String path){
        Scan s=new Scan();
        List<String> list = s.come(path);
        for (String l:list){
            try {
                //通过类名创建Class对象
                Class<?> clazz = Class.forName(l);
                if (clazz.isAnnotationPresent(Component.class)){
                    String value = clazz.getAnnotation(Component.class).value();
                    if (value.equals("")){
                        value = clazz.getSimpleName();
                        value = toLower(value);
                    }

                    Definition definition=new Definition();
                    //id=Component的值
                    if (clazz.isAnnotationPresent(Scope.class)){
                        //获取有Scope注解的类
                        String value1 = clazz.getAnnotation(Scope.class).value();
                        //不管单例还是原型都放在scope中
                        definition.setScope(value1);
                    }
                    definition.setId(value);
                    definition.setClassName(clazz);
                    prototype.put(value,definition);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    //转换成第一个字母小写
    private static String toLower(String name){
        if (Character.isLowerCase(name.charAt(0))){
            return name;
        }else
            return (new StringBuilder()).append(Character.toLowerCase(name.charAt(0))).append(name.substring(1)).toString();
    }

    //单例的容器
    private void initSingleton() throws IllegalAccessException, InstantiationException {
        //循环遍历prototype的键
        for (String a : prototype.keySet()) {
            //通过键获取Scope的值
            String scope = prototype.get(a).getScope();
            //判断scope是单例还是原型
            if ("singleton".equals(scope)){
                singleton.put(a,prototype.get(a).getClassName().newInstance());
            }
        }
    }

    public Object getBean(String value){
        String scope = prototype.get(value).getScope();
        try {
            return ("singleton".equals(scope)) ? singleton.get(value) : prototype.get(value).getClassName().newInstance();
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }
}
